/* eslint-disable no-nested-ternary */
/* eslint-disable no-param-reassign */
/* eslint-disable eqeqeq */
import { useStore } from '@/hooks';
import { Box, Button, Icon, List, Loading, Range, Search, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import styles from './TracePanel.module.scss';
import moment from 'moment';
import { DATETIME_TEXT } from '@/stores/definitions-base';

const KINDS = [
  { key: 0, title: t`进行中` },
  { key: 1, title: t`历史轨迹` },
];

const TracePanel = observer(({ ...props }) => {
  const [keyword, setKeyword] = useState('');
  const { taskMapStore: store } = useStore();

  return (
    <Box className={styles.tracePanel} {...props}>
      <Search shape="simple" type="normal" hasClear placeholder={t`查找轨迹`} style={{ width: '100%' }} value={keyword} onChange={setKeyword} />
      <Tab size="small" navClassName="tab-nav" activeKey={store.traceKind} onChange={(v) => { store.traceKind = Number(v); }}>
        {KINDS.map((k) => (
          <Tab.Item title={k.title} key={k.key} />
        ))}
      </Tab>
      <TraceList keyword={keyword} />
    </Box>
  );
});

export default TracePanel;

const PG_SIZE = 10;
const TraceList = observer(({ keyword }) => {
  const { taskMapStore: store } = useStore();
  const { mapContext: ctx } = store;
  const kind = store.traceKind;

  const [data, setData] = useState({
    loading: false,
    loadingMore: false,
    pageNo: 0,
  });

  useEffect(() => {
    // stopCarAnimation();
    ctx.reset();
    (async () => {
      await fetchData(0);
      if (data.pageNo === 0 && store.traces.length > 0) {
        store.setTrace(store.traces[0]);
      }
    })();
  }, [kind, keyword]);

  async function fetchData(pageNo) {
    setData({ ...data, loading: pageNo === 0, loadingMore: pageNo > 0 });
    await store.fetchTraces({ pageNo, keyword });
    setData({ ...data, pageNo, loading: false, loadingMore: false });
  }

  if (data.loading) return <Loading size="medium" style={{ width: '100%', height: '80%' }} />;

  return (
    <Box className="list-content">
      <List size="small" style={{ flex: 'auto' }}>
        {store.traces.map((v) => (
          <List.Item
            key={v.id}
            style={{ cursor: 'pointer', paddingRight: 4 }}
            media={<Icon className="iconfont icon-cheliang" size={18} style={{ alignSelf: 'center' }} />}
            title={v.metadata?.taskId}
            extra={store.traceKind === 0 && store.trace?.id == v.id && <Icon type="arrow-right" size="xs" />}
            description={store.trace?.id == v.id && store.traceKind === 1 ? (
              <Box spacing={4}>
                <span title={DATETIME_TEXT(v.upDate)}>{`${v.metadata?.vehicleNo}`} {moment(v.upDate).fromNow()}</span>
                <Box direction="row" spacing={10} style={{ width: '100%' }}>
                  <Button.Group size="small">
                    <Button title={ctx.animating ? t`暂停` : (ctx.paused ? t`继续` : t`回放`)} onClick={() => (ctx.animating ? store.pauseCarAnimation() : store.startCarAnimation())}><Icon className={`iconfont ${ctx.animating ? 'icon-pause' : 'icon-play'}`} /></Button>
                    <Button title={t`停止`} onClick={() => store.stopCarAnimation()}><Icon className="iconfont icon-stop" /></Button>
                  </Button.Group>
                  <span>{t`${ctx.ratio}倍速`}</span>
                  <Range value={ctx.ratio} style={{ maxWidth: 100 }} min={10} max={100} step={10} onChange={(d) => { ctx.ratio = d; }} />
                </Box>
              </Box>
            ) : <span title={DATETIME_TEXT(v.upDate)}>{`${v.metadata?.vehicleNo} ${moment(v.upDate).fromNow()}`}</span>}
            onClick={() => {
              if (store.trace?.id != v.id) {
                store.setTrace(v);
              }
            }}
          />
        ))}
        {store.traceTotal > PG_SIZE && store.traces.length < store.traceTotal &&
          <Button text style={{ width: '100%', padding: 8 }} loading={data.loadingMore} onClick={() => fetchData(data.pageNo + 1)}>{t`加载更多`}</Button>}
      </List>
    </Box >
  );
});
